const memberUser = require('../services/memberUser');

Date.prototype.Format = function (fmt) { // author: meizz
	var o = {
		"M+": this.getMonth() + 1, // 月份
		"d+": this.getDate(), // 日
		"h+": this.getHours(), // 小时
		"m+": this.getMinutes(), // 分
		"s+": this.getSeconds(), // 秒
		"q+": Math.floor((this.getMonth() + 3) / 3), // 季度
		"S": this.getMilliseconds() // 毫秒
	};
	if (/(y+)/.test(fmt))
		fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
	for (var k in o)
		if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
		return fmt;
	}

module.exports = function(io){
	var users = {};//socket注册用户
	io.on('connection',function(socket){
		
		console.log('socket 连接成功!')
		//用户注册登录
		socket.on('login',(uid)=>{
			console.log(uid)
			socket.name  = uid;
			users[uid] = socket.id;
		});
		//用户一对一消息发送
		socket.on('msg',(msg,fromid,toid)=>{
			//发送给对方
			memberUser.insertMsg({//存一对一消息
				fromId:fromid,
				toid:toid,
				messages:msg.messages,
				types:msg.types,
				time:new Date().Format("yyyy-MM-dd hh:mm:ss"),
				len:msg.len
			}).then(data=>{
				if(users[toid]){
					socket.to(users[toid]).emit('msg',msg,fromid)
				}
			})
		});
		//用户离开
		socket.on('disconnecting',()=>{
			console.log(users)
			if(users.hasOwnProperty(socket.name)){
				delete users[socket.name]
				console.log(users)
			}
			console.log(socket.id+"离开")
		})
	 })
}